package cn.edu.njust.alg.leetcode;

import cn.edu.njust.utils.ListNodeUtils;
import cn.edu.njust.utils.TreeNodeUtils;

/**
 * 创建时间：2015年6月15日 上午11:47:37 项目名称：AlgorithmExercise
 * 
 * @author Zhou Xiumin
 * @version 1.0
 * @since JDK 1.7.0_21 文件名称：Leetcode_0_t.java 类说明：
 */
public class Leetcode_109_Convert_Sorted_List_to_Binary_Search_Tree {

	public static TreeNode sortedListToBST(ListNode head) {
		if (head == null) {
			return null;
		}
		ListNode[] nums = trans(head);
		TreeNode root = buildBST(nums, 0, nums.length - 1);
		return root;
	}

	public static TreeNode buildBST(ListNode[] nums, int begin, int end) {
		if (begin > end) {
			return null;
		} else if (begin == end) {
			TreeNode root = new TreeNode(nums[begin].val);
			root.left = null;
			root.right = null;
			return root;
		}
		int mid = (begin + end) / 2;
		TreeNode rootNode = new TreeNode(nums[mid].val);
		rootNode.left = buildBST(nums, begin, mid - 1);
		rootNode.right = buildBST(nums, mid + 1, end);
		return rootNode;
	}

	public static ListNode[] trans(ListNode head) {
		ListNode p = head;
		int count = 0;
		while (p != null) {
			count++;
			p = p.next;
		}
		ListNode[] list = new ListNode[count];
		count = 0;
		p = head;
		while (p != null) {
			list[count] = p;
			count++;
			p = p.next;
		}
		return list;
	}

	public static TreeNode buildBST(int[] nums, int begin, int end) {
		if (begin > end) {
			return null;
		} else if (begin == end) {
			TreeNode root = new TreeNode(nums[begin]);
			root.left = null;
			root.right = null;
			return root;
		}
		int mid = (begin + end) / 2;
		TreeNode rootNode = new TreeNode(nums[mid]);
		rootNode.left = buildBST(nums, begin, mid - 1);
		rootNode.right = buildBST(nums, mid + 1, end);
		return rootNode;
	}

	public static TreeNode sortedArrayToBST(int[] nums) {
		if (nums == null || nums.length == 0) {
			return null;
		}
		TreeNode root = buildBST(nums, 0, nums.length - 1);
		return root;

	}

	public static void main(String[] args) {
		int[] nums = { 1, 2, 3, 4, 5, 6, 7 };
		ListNode list = ListNodeUtils.createList(nums);
		TreeNode root = sortedArrayToBST(nums);
		TreeNode root1 = sortedListToBST(list);
		TreeNodeUtils.printList(root);
		System.out.println();
		TreeNodeUtils.printList(root1);
	}

}
